## ** 统一的后端 响应格式 author：zhaomin ** ### 
from fastapi.responses import JSONResponse
from typing import Optional, Any

from app.schemas.base.request import SuccessResponse, FailedResponse,SuccessExtra
from app.utils.app_log import logger


# 固定响应格式 
class RequestHandler:
    """
    前后端交互处理类。
    提供统一的请求解析、响应生成和异常处理功能。
    """
    @staticmethod
    def create_response(data: Any = None,code: int = 200,message: str = "Success",remarks: Optional[str] = None) -> JSONResponse:
        """创建统一的成功响应。"""
        return JSONResponse(
            content=SuccessResponse(
                code=code,
                message=message,
                remarks=remarks,
                data=data
            ).model_dump()
        )
    
    @staticmethod
    def error(message: str = "操作失败",code: int = 400,remarks: Optional[str] = None,data: Any = None) -> JSONResponse:
        """创建错误响应。"""
        return JSONResponse(status_code=code,
            content=FailedResponse(
                code=code,
                message=message,
                remarks=remarks,
                data=data
            ).model_dump()
        )

    @staticmethod
    def success_paginated(
        data: Any = None,
        total: int = 0,
        page: int = 1,
        page_size: int = 20,
        message: str = "操作成功",
        code: int = 200,
        remarks: Optional[str] = None,
        **extra_fields, # 允许传递额外字段到 SuccessExtra
    ) -> SuccessExtra: # 明确返回类型为 SuccessExtra
        """
        创建带有分页信息的统一成功响应。
        适用于列表数据查询并需要分页的场景。
        """
        return SuccessExtra(
            code=code,
            message=message,  # 使用统一的message参数
            data=data,
            total=total,
            page=page,
            page_size=page_size,
            **extra_fields # 传递任何额外字段
        )
        

    ## 这都是一些快捷方法
    @staticmethod
    def success(data: Any = None, message: str = "操作成功", remarks: Optional[str] = None ) -> JSONResponse:
        """创建成功响应的快捷方法。"""
        return RequestHandler.create_response(data=data,code=200,message=message,remarks=remarks)

    @staticmethod
    def created(data: Any = None, message: str = "创建成功", remarks: Optional[str] = None) -> JSONResponse:
        """创建201状态码响应。"""
        return RequestHandler.create_response(data=data,code=201,message=message,remarks=remarks)

    @staticmethod
    def unauthorized(message: str = "未授权访问",remarks: Optional[str] = None) -> JSONResponse:
        """创建401未授权响应。"""
        return RequestHandler.error(message=message,code=401,remarks=remarks)

    @staticmethod
    def forbidden(message: str = "权限不足", remarks: Optional[str] = None) -> JSONResponse:
        """创建403禁止访问响应。"""
        return RequestHandler.error(message=message,code=403,remarks=remarks )

    @staticmethod
    def not_found(message: str = "资源不存在", remarks: Optional[str] = None) -> JSONResponse:
        """创建404未找到响应。"""
        return RequestHandler.error(message=message,code=404,remarks=remarks)

    @staticmethod
    def validation_error(message: str = "数据验证失败",errors: Any = None,remarks: Optional[str] = None) -> JSONResponse:
        """创建422数据验证错误响应。"""
        return RequestHandler.error(message=message,code=422,remarks=remarks,data=errors)

    @staticmethod
    def server_error(message: str = "服务器内部错误", remarks: Optional[str] = "请稍后重试或联系管理员") -> JSONResponse:
        """创建500服务器错误响应。"""
        return RequestHandler.error(message=message,code=500,remarks=remarks)

    @staticmethod
    def handle_exception(e: Exception) -> JSONResponse:
        """统一处理异常并返回标准错误响应。"""
        logger.error(f"Unhandled exception: {str(e)}")
        return RequestHandler.server_error(message="发生未预期的错误", remarks=f"错误详情：{str(e)}")


RequestHandler  = RequestHandler()